<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网络五子棋</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#8B5A2B',      // 木质主色调
                        secondary: '#D2B48C',    // 木质辅助色
                        accent: '#CD853F',       // 强调色
                        dark: '#3E2723',         // 深色
                        light: '#F5F5DC',        // 浅色
                        board: '#DEB887',        // 棋盘色
                        black: '#000000',        // 黑棋
                        white: '#FFFFFF',        // 白棋
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                        serif: ['"Noto Serif SC"', 'serif'],
                    },
                    boxShadow: {
                        'piece': '0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -1px rgba(0, 0, 0, 0.2)',
                        'board': '0 10px 15px -3px rgba(0, 0, 0, 0.4), 0 4px 6px -2px rgba(0, 0, 0, 0.2)',
                    }
                },
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .text-shadow {
        text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
      }
      .board-grid {
        background-image: linear-gradient(to right, #000 1px, transparent 1px),
                         linear-gradient(to bottom, #000 1px, transparent 1px);
      }
      .piece-transition {
        transition: transform 0.3s ease, box-shadow 0.3s ease;
      }
      .piece-hover:hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 8px -1px rgba(0, 0, 0, 0.4);
      }
    }
  </style>
</head>

<body class="bg-light min-h-screen font-sans text-dark overflow-x-hidden">
    <!-- 页面容器 -->
    <div class="relative">
        <!-- 首页 -->
        <div id="home-page"
            class="min-h-screen flex flex-col items-center justify-center p-4 transition-opacity duration-500">
            <div class="absolute inset-0 bg-cover bg-center opacity-10"
                style="background-image: url('https://picsum.photos/id/175/1200/800');"></div>

            <div class="text-center mb-12 relative">
                <h1
                    class="text-[clamp(2.5rem,8vw,5rem)] font-serif font-bold text-primary mb-4 text-shadow animate-pulse">
                    网络五子棋
                </h1>
                <p class="text-[clamp(1rem,3vw,1.25rem)] text-dark/80 max-w-md mx-auto">
                    挑战全国各地的棋手，展示你的五子棋技巧，成为真正的五子棋大师
                </p>
            </div>

            <div class="relative">
                <button id="start-btn"
                    class="bg-primary hover:bg-primary/90 text-white font-bold py-4 px-12 rounded-lg text-lg shadow-lg transform transition-all duration-300 hover:scale-105 hover:shadow-xl focus:outline-none focus:ring-4 focus:ring-primary/50">
                    <i class="fa fa-play-circle mr-2"></i>开始游戏
                </button>
            </div>

            <footer class="absolute bottom-6 text-center text-dark/60 text-sm">
                <p>© 2023 网络五子棋 - 享受纯粹的棋类乐趣</p>
            </footer>
        </div>

        <!-- 登录页面 -->
        <div id="login-page" class="hidden min-h-screen flex items-center justify-center p-4">
            <div class="absolute inset-0 bg-cover bg-center opacity-10"
                style="background-image: url('https://picsum.photos/id/106/1200/800');"></div>

            <div
                class="w-full max-w-md bg-white rounded-xl shadow-2xl overflow-hidden relative z-10 transform transition-all duration-500 hover:shadow-3xl">
                <div class="p-8">
                    <div class="text-center mb-8">
                        <h2 class="text-3xl font-serif font-bold text-primary">登录</h2>
                        <p class="text-dark/60 mt-2">欢迎回来，请登录您的账号</p>
                    </div>

                    <form id="login-form" class="space-y-6">
                        <div>
                            <label for="login-username" class="block text-sm font-medium text-dark/80 mb-1">用户名</label>
                            <div class="relative">
                                <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-dark/50">
                                    <i class="fa fa-user"></i>
                                </span>
                                <input type="text" id="login-username" name="username" required
                                    class="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                                    placeholder="请输入用户名">
                            </div>
                        </div>

                        <div>
                            <label for="login-password" class="block text-sm font-medium text-dark/80 mb-1">密码</label>
                            <div class="relative">
                                <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-dark/50">
                                    <i class="fa fa-lock"></i>
                                </span>
                                <input type="password" id="login-password" name="password" required
                                    class="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                                    placeholder="请输入密码">
                            </div>
                        </div>

                        <div>
                            <button type="submit"
                                class="w-full bg-primary hover:bg-primary/90 text-white font-bold py-3 px-4 rounded-lg transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-primary/50">
                                <i class="fa fa-sign-in mr-2"></i>登录
                            </button>
                        </div>

                        <div class="text-center pt-2">
                            <p class="text-dark/70">还没有账号？
                                <button type="button" id="to-register-btn"
                                    class="text-accent hover:text-accent/80 font-medium transition-colors duration-200">
                                    立即注册
                                </button>
                            </p>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 注册页面 -->
        <div id="register-page" class="hidden min-h-screen flex items-center justify-center p-4">
            <div class="absolute inset-0 bg-cover bg-center opacity-10"
                style="background-image: url('https://picsum.photos/id/106/1200/800');"></div>

            <div
                class="w-full max-w-md bg-white rounded-xl shadow-2xl overflow-hidden relative z-10 transform transition-all duration-500 hover:shadow-3xl">
                <div class="p-8">
                    <div class="text-center mb-8">
                        <h2 class="text-3xl font-serif font-bold text-primary">注册</h2>
                        <p class="text-dark/60 mt-2">创建新账号，开始五子棋之旅</p>
                    </div>

                    <form id="register-form" class="space-y-6">
                        <div>
                            <label for="reg-username" class="block text-sm font-medium text-dark/80 mb-1">用户名</label>
                            <div class="relative">
                                <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-dark/50">
                                    <i class="fa fa-user-plus"></i>
                                </span>
                                <input type="text" id="reg-username" name="username" required
                                    class="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                                    placeholder="请设置用户名">
                            </div>
                        </div>

                        <div>
                            <label for="reg-password" class="block text-sm font-medium text-dark/80 mb-1">密码</label>
                            <div class="relative">
                                <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-dark/50">
                                    <i class="fa fa-lock"></i>
                                </span>
                                <input type="password" id="reg-password" name="password" required
                                    class="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                                    placeholder="请设置密码">
                            </div>
                        </div>

                        <div>
                            <label for="reg-confirm" class="block text-sm font-medium text-dark/80 mb-1">确认密码</label>
                            <div class="relative">
                                <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-dark/50">
                                    <i class="fa fa-lock"></i>
                                </span>
                                <input type="password" id="reg-confirm" name="confirm" required
                                    class="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary focus:border-primary transition-all"
                                    placeholder="请再次输入密码">
                            </div>
                        </div>

                        <div class="flex space-x-2">
                            <button type="submit"
                                class="flex-1 bg-primary hover:bg-primary/90 text-white font-bold py-3 px-4 rounded-lg transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-primary/50">
                                <i class="fa fa-check mr-2"></i>注册
                            </button>

                            <button type="button" id="to-login-btn"
                                class="flex-1 bg-gray-200 hover:bg-gray-300 text-dark font-bold py-3 px-4 rounded-lg transition-all duration-300 focus:outline-none">
                                <i class="fa fa-arrow-left mr-2"></i>返回
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 游戏大厅 -->
        <div id="hall-page" class="hidden min-h-screen flex flex-col">
            <header class="bg-primary text-white py-4 px-6 shadow-md">
                <div class="container mx-auto flex justify-between items-center">
                    <h1 class="text-2xl font-serif font-bold">
                        <i class="fa fa-trophy mr-2"></i>网络五子棋大厅
                    </h1>
                    <div id="user-info" class="flex items-center space-x-4">
                        <div class="hidden md:block">
                            <p class="font-medium">欢迎，<span id="hall-username">玩家</span></p>
                            <p class="text-sm text-light/80">积分: <span id="hall-points">0</span></p>
                        </div>
                        <button id="logout-btn"
                            class="bg-white/20 hover:bg-white/30 text-white px-4 py-2 rounded-lg transition-all duration-200 focus:outline-none">
                            <i class="fa fa-sign-out mr-1"></i>退出
                        </button>
                    </div>
                </div>
            </header>

            <main class="flex-1 container mx-auto p-4 md:p-8 flex flex-col items-center justify-center">
                <div
                    class="w-full max-w-2xl bg-white rounded-xl shadow-xl p-6 md:p-8 mb-8 transform transition-all duration-300 hover:shadow-2xl">
                    <div class="text-center mb-6">
                        <h2 class="text-2xl font-bold text-primary mb-2">寻找对手</h2>
                        <p class="text-dark/70">点击开始匹配，系统将为您寻找合适的对手</p>
                    </div>

                    <div class="flex justify-center">
                        <button id="start-match-btn"
                            class="bg-accent hover:bg-accent/90 text-white font-bold py-3 px-10 rounded-lg text-lg shadow-lg transform transition-all duration-300 hover:scale-105 hover:shadow-xl focus:outline-none focus:ring-4 focus:ring-accent/50">
                            <i class="fa fa-users mr-2"></i>开始匹配
                        </button>
                    </div>

                    <div id="matching-status" class="hidden mt-6 text-center">
                        <div
                            class="inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary mb-2">
                        </div>
                        <p class="text-dark/80">正在寻找对手... <span id="match-countdown">15</span>秒</p>
                        <button id="cancel-match-btn"
                            class="mt-4 text-accent hover:text-accent/80 font-medium transition-colors duration-200">
                            <i class="fa fa-times-circle mr-1"></i>取消匹配
                        </button>
                    </div>
                </div>

                <div class="w-full max-w-2xl bg-white rounded-xl shadow-lg p-6">
                    <h3 class="text-xl font-bold text-primary mb-4 flex items-center">
                        <i class="fa fa-info-circle mr-2"></i>游戏规则
                    </h3>
                    <ul class="space-y-2 text-dark/80">
                        <li class="flex items-start">
                            <i class="fa fa-check-circle text-accent mt-1 mr-2"></i>
                            <span>黑白双方轮流在棋盘上落子，先形成五子连线者获胜</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fa fa-check-circle text-accent mt-1 mr-2"></i>
                            <span>五子连线可以是横、竖或斜向的连续五个同色棋子</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fa fa-check-circle text-accent mt-1 mr-2"></i>
                            <span>获胜方将获得积分奖励，失败方将损失部分积分</span>
                        </li>
                    </ul>
                </div>
            </main>

            <footer class="bg-dark text-white/80 py-4 px-6 text-center text-sm">
                <p>© 2023 网络五子棋 - 公平竞技，友谊第一</p>
            </footer>
        </div>

        <!-- 游戏房间 -->
        <div id="room-page" class="hidden min-h-screen flex flex-col">
            <header class="bg-primary text-white py-3 px-6 shadow-md">
                <div class="container mx-auto flex justify-between items-center">
                    <div>
                        <h1 class="text-xl font-serif font-bold">
                            <i class="fa fa-gamepad mr-2"></i>游戏房间 #<span id="room-id">0</span>
                        </h1>
                    </div>
                    <div class="flex items-center space-x-6">
                        <div class="flex items-center">
                            <div class="w-4 h-4 rounded-full bg-white mr-2"></div>
                            <span id="white-player">白方: 加载中...</span>
                        </div>
                        <div class="flex items-center">
                            <div class="w-4 h-4 rounded-full bg-black mr-2"></div>
                            <span id="black-player">黑方: 加载中...</span>
                        </div>
                        <button id="leave-room-btn"
                            class="bg-white/20 hover:bg-white/30 text-white px-3 py-1 rounded-lg transition-all duration-200 focus:outline-none text-sm">
                            <i class="fa fa-sign-out mr-1"></i>离开房间
                        </button>
                    </div>
                </div>
            </header>

            <main class="flex-1 container mx-auto p-4 md:p-6 flex flex-col md:flex-row gap-6">
                <!-- 棋盘区域 -->
                <div class="flex-1 flex flex-col items-center justify-center">
                    <div id="game-message" class="mb-4 text-center text-lg font-medium text-primary min-h-[2rem]">
                        游戏即将开始，请等待双方准备...
                    </div>

                    <div class="relative">
                        <div id="board-container" class="bg-board rounded-lg shadow-board p-2 md:p-4">
                            <div id="board"
                                class="board-grid w-[300px] h-[300px] md:w-[450px] md:h-[450px] bg-board relative"
                                style="background-size: calc(100% - 1px) calc(100% - 1px); background-position: 0 0; background-repeat: no-repeat;">
                                <!-- 棋子将通过JS动态生成 -->
                            </div>
                        </div>

                        <!-- 胜利遮罩 -->
                        <div id="win-overlay"
                            class="hidden absolute inset-0 bg-black/50 rounded-lg flex items-center justify-center">
                            <div
                                class="bg-white p-6 rounded-xl text-center shadow-xl transform transition-all duration-500 scale-110">
                                <h2 class="text-2xl font-bold text-primary mb-4" id="winner-text">白方获胜!</h2>
                                <button id="restart-btn"
                                    class="bg-accent hover:bg-accent/90 text-white font-bold py-2 px-6 rounded-lg transition-all duration-300 focus:outline-none">
                                    <i class="fa fa-refresh mr-1"></i>再来一局
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 聊天区域 -->
                <div class="w-full md:w-80 bg-white rounded-xl shadow-lg flex flex-col h-[400px] md:h-[500px]">
                    <div class="p-3 border-b border-gray-200 bg-gray-50">
                        <h3 class="font-bold text-dark flex items-center">
                            <i class="fa fa-comments text-primary mr-2"></i>聊天框
                        </h3>
                    </div>

                    <div id="chat-messages" class="flex-1 p-3 overflow-y-auto space-y-3">
                        <!-- 聊天消息将通过JS动态生成 -->
                        <div class="text-center text-sm text-gray-500">
                            聊天记录将显示在这里
                        </div>
                    </div>

                    <div class="p-3 border-t border-gray-200">
                        <form id="chat-form" class="flex space-x-2">
                            <input type="text" id="chat-input" placeholder="输入消息..."
                                class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                            <button type="submit"
                                class="bg-primary hover:bg-primary/90 text-white p-2 rounded-lg transition-all duration-200">
                                <i class="fa fa-paper-plane"></i>
                            </button>
                        </form>
                    </div>
                </div>
            </main>

            <footer class="bg-dark text-white/80 py-3 px-6 text-center text-sm">
                <p>提示: 点击棋盘落子，先连成五子者获胜</p>
            </footer>
        </div>
    </div>

    <script>
        // 页面元素
        const pages = {
            home: document.getElementById('home-page'),
            login: document.getElementById('login-page'),
            register: document.getElementById('register-page'),
            hall: document.getElementById('hall-page'),
            room: document.getElementById('room-page')
        };

        // WebSocket连接
        let ws = null;
        let isMatching = false;
        let matchCountdown = 15;
        let countdownInterval = null;
        let currentUserId = null;
        let currentRoomId = null;
        let isWhitePlayer = false;
        let gameBoard = Array(15).fill().map(() => Array(15).fill(0)); // 0:空, 1:白, 2:黑

        // 页面跳转函数
        function showPage(pageName) {
            Object.keys(pages).forEach(key => {
                pages[key].classList.add('hidden');
            });
            pages[pageName].classList.remove('hidden');

            // 房间页面显示时的额外处理
            if (pageName === 'room') {
                // 强制重置游戏状态
                resetGame();
                // 显示加载提示
                document.getElementById('game-message').textContent = '正在连接房间...';
                document.getElementById('white-player').textContent = '白方: 加载中...';
                document.getElementById('black-player').textContent = '黑方: 加载中...';
                // 重新连接房间WebSocket
                connectToRoomWebSocket();
            }
        }

        // 初始化页面
        function init() {
            // 首页按钮
            document.getElementById('start-btn').addEventListener('click', () => {
                showPage('login');
            });

            // 登录页面按钮
            document.getElementById('to-register-btn').addEventListener('click', () => {
                showPage('register');
            });

            // 注册页面按钮
            document.getElementById('to-login-btn').addEventListener('click', () => {
                showPage('login');
            });

            // 登录表单提交
            document.getElementById('login-form').addEventListener('submit', (e) => {
                e.preventDefault();
                const username = document.getElementById('login-username').value;
                const password = document.getElementById('login-password').value;

                // 模拟登录请求
                fetch('/login', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ name: username, passwd: password })
                })
                    .then(res => res.json())
                    .then(data => {
                        if (data.result) {
                            // 登录成功，获取用户信息
                            fetch('/info')
                                .then(res => res.json())
                                .then(userInfo => {
                                    currentUserId = userInfo.id;
                                    document.getElementById('hall-username').textContent = userInfo.name;
                                    document.getElementById('hall-points').textContent = userInfo.points || 0;

                                    // 连接大厅WebSocket
                                    connectToHallWebSocket();
                                    showPage('hall');
                                });
                        } else {
                            alert(data.reason || '登录失败');
                        }
                    })
                    .catch(err => console.error('登录失败:', err));
            });

            // 注册表单提交
            document.getElementById('register-form').addEventListener('submit', (e) => {
                e.preventDefault();
                const username = document.getElementById('reg-username').value;
                const password = document.getElementById('reg-password').value;
                const confirm = document.getElementById('reg-confirm').value;

                if (password !== confirm) {
                    alert('两次输入的密码不一致');
                    return;
                }

                // 模拟注册请求
                fetch('/register', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ name: username, passwd: password })
                })
                    .then(res => res.json())
                    .then(data => {
                        if (data.result) {
                            alert('注册成功，请登录');
                            showPage('login');
                        } else {
                            alert(data.reason || '注册失败');
                        }
                    })
                    .catch(err => console.error('注册失败:', err));
            });

            // 大厅页面按钮
            document.getElementById('start-match-btn').addEventListener('click', startMatching);
            document.getElementById('cancel-match-btn').addEventListener('click', cancelMatching);
            document.getElementById('logout-btn').addEventListener('click', logout);

            // 房间页面按钮
            document.getElementById('leave-room-btn').addEventListener('click', leaveRoom);
            document.getElementById('restart-btn').addEventListener('click', restartGame);

            // 聊天表单提交
            document.getElementById('chat-form').addEventListener('submit', (e) => {
                e.preventDefault();
                const input = document.getElementById('chat-input');
                const message = input.value.trim();

                if (message && ws) {
                    ws.send(JSON.stringify({
                        op_type: 'chat',
                        room_id: currentRoomId,
                        uid: currentUserId,
                        message: message
                    }));
                    input.value = '';
                }
            });

            // 初始化棋盘
            initBoard();
        }

        // 连接大厅WebSocket
        function connectToHallWebSocket() {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${protocol}//${window.location.host}/hall`;

            ws = new WebSocket(wsUrl);

            ws.onopen = () => {
                console.log('大厅WebSocket连接成功');
            };

            ws.onmessage = (event) => {
                const data = JSON.parse(event.data);
                console.log('收到大厅消息:', data);

                if (data.op_type === 'match_success' && data.result) {
                    // 匹配成功后，先关闭大厅连接，再进入房间（确保连接顺序正确）
                    cancelMatching();
                    if (ws) {
                        ws.close(1000, "匹配成功，切换到房间");
                    }
                    // 延迟500ms确保连接关闭后再切换页面（避免连接冲突）
                    setTimeout(() => {
                        showPage('room');
                    }, 500);
                } else if (data.op_type === 'hall_ready') {
                    console.log('大厅准备就绪');
                }
            };

            ws.onclose = () => {
                console.log('大厅WebSocket连接关闭');
                ws = null;
            };

            ws.onerror = (error) => {
                console.error('大厅WebSocket错误:', error);
            };
        }

        // 连接房间WebSocket
        function connectToRoomWebSocket() {
            // 先关闭可能存在的旧连接
            if (ws) {
                ws.close(1000, "切换到房间页面");
            }

            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${protocol}//${window.location.host}/room`;

            console.log(`尝试连接房间WebSocket: ${wsUrl}`);
            ws = new WebSocket(wsUrl);

            // 记录连接开始时间，用于超时判断
            const connectStartTime = Date.now();

            // 连接超时检测（5秒）
            const connectTimeout = setTimeout(() => {
                if (ws.readyState !== WebSocket.OPEN) {
                    console.error("房间WebSocket连接超时");
                    showPage('hall'); // 超时返回大厅
                    alert("连接房间失败，请重新匹配");
                }
            }, 5000);

            ws.onopen = () => {
                clearTimeout(connectTimeout);
                console.log('房间WebSocket连接成功');
                // 连接成功后立即发送房间就绪请求（关键：主动请求初始化信息）
                ws.send(JSON.stringify({
                    op_type: 'room_init',
                    uid: currentUserId
                }));
            };

            ws.onmessage = (event) => {
                try {
                    const data = JSON.parse(event.data);
                    console.log('收到房间消息:', data);

                    // 重点处理room_ready消息（房间初始化核心）
                    if (data.op_type === 'room_ready') {
                        if (!data.result) {
                            alert('进入房间失败: ' + (data.reason || '未知错误'));
                            showPage('hall');
                            return;
                        }

                        // 关键：打印完整数据用于排查字段问题
                        console.log('房间初始化数据:', data);

                        // 房间ID处理（增加容错，避免显示"未知"）
                        currentRoomId = data.room_id || data.roomId || '未获取'; // 兼容可能的字段名差异
                        document.getElementById('room-id').textContent = currentRoomId;
                        if (!data.room_id && !data.roomId) {
                            console.warn('后端返回的room_ready消息中未包含房间ID字段');
                        }

                        // 玩家信息（已正常显示，保留）
                        document.getElementById('white-player').textContent = `白方: ${data.white_name || '玩家' + data.white_id}`;
                        document.getElementById('black-player').textContent = `黑方: ${data.black_name || '玩家' + data.black_id}`;

                        isWhitePlayer = data.uid === data.white_id;

                        // 强制重新初始化棋盘（增加日志确认执行）
                        console.log('开始初始化棋盘...');
                        resetGame();
                        initBoard(); // 确保执行

                        // 更新游戏提示
                        document.getElementById('game-message').textContent =
                            isWhitePlayer ? '游戏开始，您是白方，先行落子' : '游戏开始，您是黑方，请等待白方落子';
                    } else if (data.op_type === 'chess') {
                        handleChessMove(data);
                    } else if (data.op_type === 'chat' && data.result) {
                        addChatMessage(data.uid, data.message);
                    } else if (data.op_type === 'exit') {
                        document.getElementById('game-message').textContent = data.reason || '对方已离开房间';
                        if (data.winner) {
                            document.getElementById('winner-text').textContent =
                                data.winner === currentUserId ? '恭喜您获胜!' : '对手离开，您获胜!';
                            document.getElementById('win-overlay').classList.remove('hidden');
                        }
                    }
                } catch (e) {
                    console.error('解析房间消息失败:', e, '原始消息:', event.data);
                }
            };

            ws.onclose = (event) => {
                clearTimeout(connectTimeout);
                console.log('房间WebSocket关闭，代码:', event.code, '原因:', event.reason);
                ws = null;
                // 非主动关闭时提示用户
                if (event.code !== 1000) {
                    alert('与房间连接已断开，请重新匹配');
                    showPage('hall');
                }
            };

            ws.onerror = (error) => {
                console.error('房间WebSocket错误:', error);
                alert('连接房间时发生错误');
            };
        }

        // 开始匹配
        function startMatching() {
            if (ws && !isMatching) {
                ws.send(JSON.stringify({ op_type: 'match_start' }));
                isMatching = true;
                document.getElementById('start-match-btn').classList.add('hidden');
                document.getElementById('matching-status').classList.remove('hidden');

                // 开始倒计时
                matchCountdown = 15;
                document.getElementById('match-countdown').textContent = matchCountdown;
                countdownInterval = setInterval(() => {
                    matchCountdown--;
                    document.getElementById('match-countdown').textContent = matchCountdown;

                    if (matchCountdown <= 0) {
                        cancelMatching();
                    }
                }, 1000);
            }
        }

        // 取消匹配
        function cancelMatching() {
            if (ws && isMatching) {
                ws.send(JSON.stringify({ op_type: 'match_stop' }));
                isMatching = false;
                document.getElementById('start-match-btn').classList.remove('hidden');
                document.getElementById('matching-status').classList.add('hidden');

                // 清除倒计时
                if (countdownInterval) {
                    clearInterval(countdownInterval);
                    countdownInterval = null;
                }
            }
        }

        // 退出登录
        function logout() {
            if (ws) {
                ws.close();
                ws = null;
            }
            currentUserId = null;
            showPage('login');
        }

        // 离开房间
        function leaveRoom() {
            if (ws) {
                ws.send(JSON.stringify({
                    op_type: 'exit',
                    room_id: currentRoomId,
                    uid: currentUserId
                }));
                ws.close();
                ws = null;
            }

            // 重置游戏状态
            resetGame();
            connectToHallWebSocket();
            showPage('hall');
        }

        // 初始化棋盘
        function initBoard() {
            const boardContainer = document.getElementById('board-container');
            const board = document.getElementById('board');

            // 1. 检查容器是否存在（关键：避免DOM元素未找到）
            if (!boardContainer || !board) {
                console.error('棋盘容器或棋盘元素不存在！请检查HTML中的id是否正确');
                alert('加载棋盘失败：页面元素缺失');
                return;
            }

            // 2. 强制清空并设置基础样式（确保不被遮挡）
            board.innerHTML = ''; // 清空旧内容
            boardContainer.style.display = 'block'; // 确保容器可见
            boardContainer.style.width = '320px'; // 容器宽度（略大于棋盘）
            boardContainer.style.height = '320px';
            if (window.innerWidth >= 768) {
                boardContainer.style.width = '470px';
                boardContainer.style.height = '470px';
            }

            // 3. 棋盘基础样式（确保可见）
            board.style.width = '300px';
            board.style.height = '300px';
            board.style.margin = '10px'; // 与容器保持间距，避免边框被遮挡
            if (window.innerWidth >= 768) {
                board.style.width = '450px';
                board.style.height = '450px';
            }
            board.style.backgroundColor = '#DEB887'; // 明确棋盘色（避免继承透明）
            board.style.position = 'relative'; // 确保子元素绝对定位有效
            board.style.backgroundSize = 'calc(100% - 1px) calc(100% - 1px)';
            board.style.backgroundImage = `linear-gradient(to right, #000 1px, transparent 1px),
                               linear-gradient(to bottom, #000 1px, transparent 1px)`;
            board.style.backgroundPosition = '0 0';
            board.style.backgroundRepeat = 'no-repeat';

            // 4. 重新创建15x15棋盘格子（增加循环日志）
            let cellCount = 0;
            for (let i = 0; i < 15; i++) {
                for (let j = 0; j < 15; j++) {
                    const cell = document.createElement('div');
                    cell.className = 'absolute cursor-pointer transition-all duration-200 hover:bg-black/10';
                    cell.style.width = `calc(100% / 15)`;
                    cell.style.height = `calc(100% / 15)`;
                    cell.style.left = `calc(${j} * 100% / 15)`;
                    cell.style.top = `calc(${i} * 100% / 15)`;
                    cell.dataset.row = i;
                    cell.dataset.col = j;
                    cell.addEventListener('click', () => handleCellClick(i, j));
                    board.appendChild(cell);
                    cellCount++;
                }
            }

            // 5. 确认格子创建数量（15x15=225个）
            console.log(`棋盘格子创建完成，共${cellCount}个（预期225个）`);
            if (cellCount !== 225) {
                console.error('棋盘格子数量异常，可能循环逻辑错误');
            }
        }

        // 处理棋盘点击
        function handleCellClick(row, col) {
            // 检查是否可以落子
            if (!ws || !currentRoomId || gameBoard[row][col] !== 0) {
                return;
            }

            // 发送落子请求
            ws.send(JSON.stringify({
                op_type: 'chess',
                room_id: currentRoomId,
                uid: currentUserId,
                row: row,
                col: col
            }));
        }

        // 处理落子结果
        function handleChessMove(data) {
            if (!data.result) {
                alert(data.reason || '落子失败');
                return;
            }

            const row = data.row;
            const col = data.col;
            const uid = data.uid;

            // 更新棋盘数据
            const isWhite = uid === document.getElementById('white-player').textContent.split(' ')[1];
            gameBoard[row][col] = isWhite ? 1 : 2;

            // 在界面上绘制棋子
            drawPiece(row, col, isWhite);

            // 更新游戏状态
            if (data.winner) {
                document.getElementById('winner-text').textContent =
                    data.winner === currentUserId ? '恭喜您获胜!' : '很遗憾，您输了!';
                document.getElementById('win-overlay').classList.remove('hidden');
                document.getElementById('game-message').textContent = '游戏结束';
            } else {
                // 提示轮到对方落子
                document.getElementById('game-message').textContent =
                    `轮到${isWhite ? '黑' : '白'}方落子`;
            }
        }

        // 绘制棋子
        function drawPiece(row, col, isWhite) {
            const board = document.getElementById('board');
            const piece = document.createElement('div');

            // 计算棋子位置和大小
            const size = '85%';
            const left = `calc(${col} * 100% / 15 + 7.5%)`;
            const top = `calc(${row} * 100% / 15 + 7.5%)`;

            piece.className = `absolute rounded-full piece-transition piece-hover shadow-piece`;
            piece.style.width = size;
            piece.style.height = size;
            piece.style.left = left;
            piece.style.top = top;
            piece.style.backgroundColor = isWhite ? 'white' : 'black';
            piece.style.border = isWhite ? '1px solid #ccc' : '1px solid #333';

            // 添加动画效果
            piece.style.transform = 'scale(0)';
            board.appendChild(piece);

            // 触发动画
            setTimeout(() => {
                piece.style.transform = 'scale(1)';
            }, 10);
        }

        // 添加聊天消息
        function addChatMessage(uid, message) {
            const chatContainer = document.getElementById('chat-messages');

            // 清除初始提示
            if (chatContainer.querySelector('.text-gray-500')) {
                chatContainer.innerHTML = '';
            }

            const messageDiv = document.createElement('div');
            const isCurrentUser = uid === currentUserId;

            messageDiv.className = `flex ${isCurrentUser ? 'justify-end' : 'justify-start'}`;
            messageDiv.innerHTML = `
        <div class="${isCurrentUser ? 'bg-primary text-white' : 'bg-gray-100 text-dark'} 
                   rounded-lg px-3 py-2 max-w-[80%]">
          <p class="text-sm ${!isCurrentUser ? 'text-gray-500' : ''} mb-1">
            ${isCurrentUser ? '我' : `玩家 ${uid}`}
          </p>
          <p>${message}</p>
        </div>
      `;

            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        // 重置游戏
        function resetGame() {
            const board = document.getElementById('board');
            if (board) {
                // 只清空棋子，保留格子（避免重复创建格子）
                const pieces = board.querySelectorAll('div[class*="rounded-full"]'); // 只匹配棋子
                pieces.forEach(piece => piece.remove());
            }
            gameBoard = Array(15).fill().map(() => Array(15).fill(0)); // 重置数据
            currentRoomId = null;
            document.getElementById('win-overlay').classList.add('hidden');
            document.getElementById('chat-messages').innerHTML = `
                <div class="text-center text-sm text-gray-500">聊天记录将显示在这里</div>
            `;
            console.log('游戏状态已重置');
        }

        // 重新开始游戏
        function restartGame() {
            resetGame();
            document.getElementById('game-message').textContent =
                isWhitePlayer ? '游戏重新开始，您是白方，先行' : '游戏重新开始，您是黑方，请等待白方落子';
        }

        // 页面加载完成后初始化
        window.addEventListener('DOMContentLoaded', init);
    </script>
</body>

</html>